{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "求解最优解"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "迭代  297  次，连续  200  次没有接受新解，算法终止！\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([7.96165581])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 自定义目标函数C\n",
    "def C(s):\n",
    "    return 1/(s*np.sin(s)+12)\n",
    "\n",
    "# 初始化\n",
    "# 设定初始温度\n",
    "t0 = np.var(np.random.uniform(0,12.55,100))\n",
    "\n",
    "# 设定初始解\n",
    "s0 = np.random.uniform(0,12.55,1)\n",
    "\n",
    "# 设定迭代次数\n",
    "iters = 3000\n",
    "\n",
    "# 设定终止条件，连续ct个新解都没有接受时终止算法\n",
    "ct = 200\n",
    "ct_array = []\n",
    "\n",
    "# 保存历史最好的状态，默认取上边界值\n",
    "best = 12.55\n",
    "\n",
    "for t in range(1,iters+1):\n",
    "    # 在s0附近，产生新解，但又能包含定义内的所有值\n",
    "    s1 = np.random.normal(s0,2,1)\n",
    "    while s1 < 0 or s1 > 12.55:\n",
    "        s1 = np.random.normal(s0,2,1)\n",
    "    # 计算能量增量\n",
    "    delta_t = C(s1) - C(s0)\n",
    "    if delta_t < 0:\n",
    "        s0 = s1\n",
    "        ct_array.append(1)\n",
    "    else:\n",
    "        p = np.exp(-delta_t/t0)\n",
    "        if np.random.uniform(0,1) < p:\n",
    "            s0 = s1\n",
    "            ct_array.append(1)\n",
    "        else:\n",
    "            ct_array.append(0)\n",
    "    \n",
    "    best = s0 if C(s0) < C(best) else best\n",
    "\n",
    "    # 更新温度\n",
    "    t0 = t0/np.log(1+t)\n",
    "    \n",
    "    # 检查终止条件\n",
    "    if len(ct_array) > ct and np.sum(ct_array[-ct:]) == 0:\n",
    "        print(\"迭代 \",t,\" 次，连续 \",ct,\" 次没有接受新解，算法终止！\")\n",
    "        break\n",
    "    \n",
    "# 状态最终停留位置\n",
    "s0\n",
    "# array([7.98092592])\n",
    "\n",
    "# 最佳状态，即对应最优解的状态\n",
    "best\n",
    "# 迭代  363  次，连续  200  次没有接受新解，算法终止！\n",
    "# array([7.98092592])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
